package com.cppba.alipay.controller;

import com.cppba.alipay.base.exception.AlipayException;
import com.cppba.alipay.base.response.AlipayResponse;
import com.cppba.alipay.bizcontent.AlipayTradeQueryBizContent;
import com.cppba.alipay.properties.AlipayProperties;
import com.cppba.alipay.request.AlipayTradeQueryRequest;
import com.cppba.alipay.response.AlipayTradeQueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一收单线下交易查询
 *
 * @author winfed
 * @create 2017-10-23 17:27
 */
@Slf4j
@Controller
@RequestMapping("/alipay")
public class AlipayTradeQueryController {

    private final AlipayProperties alipayProperties;

    @Autowired
    public AlipayTradeQueryController(AlipayProperties alipayProperties) {
        this.alipayProperties = alipayProperties;
    }

    /**
     * 交易查询
     *
     * @return 查询结果
     */
    @RequestMapping(value = "/trade/query", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public AlipayResponse doTradeQuery(String outTradeNo) {
        // http://127.0.0.1:8080/alipay/trade/query
        // 模拟数据
        outTradeNo = StringUtils.isBlank(outTradeNo) ? "12345" : outTradeNo;
        // 业务参数
        AlipayTradeQueryBizContent alipayTradeQueryBizContent = new AlipayTradeQueryBizContent();
        alipayTradeQueryBizContent.setOutTradeNo(outTradeNo);
        // 请求构建对象
        AlipayTradeQueryRequest alipayTradeQueryRequest = new AlipayTradeQueryRequest(alipayProperties.getIsTest(),
                alipayProperties.getAppId(), alipayProperties.getPrivateKey(), alipayProperties.getAlipayPublicKey(),
                alipayProperties.getSignType(), alipayTradeQueryBizContent);
        try {
            // 发送请求，获取调用结果
            AlipayTradeQueryResponse response = alipayTradeQueryRequest.createResponse();
            // 判断是否返回成功，若失败打印日志
            if (!response.isSuccess()) {
                log.error("{}", response.getServiceErrorLog());
            }
            // 打印返回结果
            log.info(response.toString());
            return response;
        } catch (AlipayException e) {
            log.error("", e);
        }
        return null;
    }
}
